// 测试摇号结束时的弹窗功能
const API_BASE = 'http://localhost:5000';

async function testDrawEnd() {
    console.log('🧪 开始测试摇号结束功能...\n');
    
    try {
        // 1. 重置数据
        console.log('1. 重置数据...');
        const resetResponse = await fetch(`${API_BASE}/api/reset`, {
            method: 'POST'
        });
        const resetResult = await resetResponse.json();
        console.log('✓ 数据重置成功:', resetResult.message);
        
        // 2. 获取配置信息
        console.log('\n2. 获取配置信息...');
        const configResponse = await fetch(`${API_BASE}/api/config`);
        const config = await configResponse.json();
        console.log('✓ 配置信息:', config);
        
        const totalParticipants = config.total_participants;
        const groups = config.groups;
        
        // 3. 填满所有名额（除了最后一个）
        console.log(`\n3. 填满 ${totalParticipants - 1} 个名额...`);
        for (let i = 1; i < totalParticipants; i++) {
            const drawResponse = await fetch(`${API_BASE}/api/draw`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ name: `测试队长${i}` })
            });
            
            const drawResult = await drawResponse.json();
            if (drawResult.success) {
                console.log(`✓ 队长${i} 抽中 ${drawResult.group} 组`);
            } else {
                console.log(`❌ 队长${i} 摇号失败:`, drawResult.error);
            }
            
            // 添加小延迟避免请求过快
            await new Promise(resolve => setTimeout(resolve, 100));
        }
        
        // 4. 检查当前状态
        console.log('\n4. 检查当前分组状态...');
        const groupsResponse = await fetch(`${API_BASE}/api/groups`);
        const currentGroups = await groupsResponse.json();
        const totalDrawn = Object.values(currentGroups).reduce((sum, members) => sum + members.length, 0);
        console.log(`✓ 当前已抽签人数: ${totalDrawn}/${totalParticipants}`);
        
        // 5. 尝试最后一次摇号（应该成功）
        console.log('\n5. 进行最后一次摇号...');
        const lastDrawResponse = await fetch(`${API_BASE}/api/draw`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ name: `最后队长` })
        });
        
        const lastDrawResult = await lastDrawResponse.json();
        if (lastDrawResult.success) {
            console.log(`✓ 最后队长 抽中 ${lastDrawResult.group} 组`);
        } else {
            console.log(`❌ 最后队长 摇号失败:`, lastDrawResult.error);
        }
        
        // 6. 尝试再次摇号（应该失败并返回"摇号已结束"）
        console.log('\n6. 尝试在名额满后再次摇号...');
        const overDrawResponse = await fetch(`${API_BASE}/api/draw`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ name: `超额队长` })
        });
        
        const overDrawResult = await overDrawResponse.json();
        if (!overDrawResult.success) {
            console.log('✓ 正确拒绝超额摇号:', overDrawResult.error);
            
            // 检查错误信息是否包含关键词
            if (overDrawResult.error.includes('摇号已结束') || overDrawResult.error.includes('所有名额已满')) {
                console.log('✅ 错误信息包含正确的关键词，前端应该显示结束弹窗');
            } else {
                console.log('⚠️  错误信息不包含预期关键词，可能需要调整前端判断逻辑');
            }
        } else {
            console.log('❌ 超额摇号不应该成功');
        }
        
        console.log('\n🎉 测试完成！');
        console.log('现在可以在前端 http://localhost:5173/ 测试以下场景：');
        console.log('1. 点击"开始抽签"按钮 - 应该直接显示"摇号已结束"弹窗');
        console.log('2. 如果输入姓名尝试摇号 - 应该显示"摇号已结束"弹窗而不是白屏');
        
    } catch (error) {
        console.error('❌ 测试失败:', error.message);
    }
}

testDrawEnd();
